<!--
 * @Author: Mcc
 * @Date: 2024-08-20 10:48:55
 * @LastEditors: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @LastEditTime: 2024-10-08 16:49:23
 * @FilePath: \ft-apply-admin\src\views\base\login\LoginForm.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by Mcc, All Rights Reserved. 
-->
<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form v-show="getShow" ref="formRef" layout="vertical" class="enter-x p-4" :model="formData" :rules="loginFormRules"
    @keypress.enter="getCode">
    <FormItem name="phone" label="账号" class="enter-x" >
      <Input v-model:value="formData.phone" size="large" :placeholder="t('sys.login.userName')"
        class="fix-auto-fill" />
    </FormItem>
    <FormItem name="password" label="密码"  class="enter-x" >
      <InputPassword v-model:value="formData.password" size="large" visibility-toggle
        :placeholder="t('sys.login.password')" class="fix-auto-fill" />
    </FormItem>
    <Row class="enter-x">
      <Col :span="12">
      <FormItem  >
        <!-- No logic, you need to deal with it yourself -->
        <Checkbox v-model:checked="rememberMe" size="small" @change="rememberMeChange">
          {{ t('sys.login.autoLogin') }}
        </Checkbox>
      </FormItem>
      </Col>
      <Col :span="12">
      <FormItem :style="{ 'text-align': 'right'}" >
        <a-button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
          {{ t('sys.login.forgetPassword') }}
        </a-button>
      </FormItem>
      </Col>
    </Row>

    <FormItem class="enter-x login-btn">
      <a-button type="primary" size="large" block :loading="loading" @click="getCode">
        <!-- {{ t('sys.login.loginButton') }} -->
        登 录
      </a-button>
    </FormItem>
    <Col :span="24">
    <FormItem class="enter-x">
      <div class='update-time'>
        更新时间：{{appInfo.lastBuildTime}}
      </div>
    </FormItem>
  </Col>
  </Form>
  <Verify ref="verify" mode="pop" :captcha-type="captchaType" :img-size="{ width: '360px', height: '180px' }"
    @success="handleLogin" />
</template>


<script lang="ts" setup>
import { computed, reactive, ref, unref, onMounted } from 'vue'
import { Checkbox, Col, Form, Input, Row, message } from 'ant-design-vue'
const appInfo =computed(()=>{
  return __APP_INFO__ 
})
import LoginFormTitle from './LoginFormTitle.vue'

import { LoginStateEnum, useLoginState } from './useLogin'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'

import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { useGlobSetting } from '@/hooks/setting'
import { useDesign } from '@/hooks/web/useDesign'
import { Verify } from '@/components/Verifition'
import { getTenantByWebsite, getTenantIdByName } from '@/api/base/login'
import { useRouter } from 'vue-router'
import {userLogin} from '@/api/applay/login/login'

import { comStores } from '@/store/common/comStore';

const store = comStores();
import { createPermissionGuard } from '@/router/guard/permissionGuard.ts'

const router = useRouter();
const FormItem = Form.Item
const InputPassword = Input.Password
const { t } = useI18n()
const { notification, createErrorModal,createMessage } = useMessage()
const { prefixCls } = useDesign('login')
const  userStore = useUserStore()
const permissionStore = usePermissionStore()
const { setLoginState, getLoginState } = useLoginState()
const formRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字

console.log('userStore', userStore.loginUserInfo)

const formData = reactive({
  phone: '', // 18326099024
  password: '', // 123456
})
if (userStore.loginUserInfo) {
  formData.phone = userStore.loginUserInfo.phone
  formData.password = userStore.loginUserInfo.password
}


const loginFormRules = {
  phone: [
    { required: true, message: '请填写手机号！', trigger: 'blur' },
    { len: 11, message: '手机号格式错误',pattern:/^(1[3-9]\d{9}|(8|9)\d{7})$/, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ],
}
const rememberMeChange = (e: any) => {
  console.log('e', e)
}
// onKeyStroke('Enter', handleLogin);
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
interface Role {
    roleId: number;
    roleName: string;
}

function extractRoleIdsAsStrings(roles: Role[]): string[] {
    return roles.map(role => role.roleId.toString());
}
// 登录
async function getCode() {
  formRef.value
    .validate()
    .then(async() => {
      const res = await userLogin(formData);
      if(res.code){
        createMessage.error(res.msg)
        return;
      }else{
        createMessage.success("登录成功！")
        await store.setUserInFor(res);
        await userStore.setAccessToken(res.token)
        await userStore.setLoginUserInfo(formData)
        await userStore.setRoleList(extractRoleIdsAsStrings(res.userRoleList));
        await userStore.setUserInfo(res);
        handleLogin();
      }
    })
    .catch(error => {
      console.log('error', error);
    });
}

async function handleLogin() {
  try {
    // loading.value = true
    // const routeList = await permissionStore.buildRoutesAction()
    // console.log(routeList, 'routes')
    // routeList.forEach((route) => {
    //   try {
    //     router.addRoute(route)
    //   }
    //   catch (e) { }
    // })
    router.push('/TodayEvent/todo')  //wangmm
    createPermissionGuard(router)
    return
  }
  catch (error) {
    createErrorModal({
      title: t('sys.api.errorTip'),
      content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    })
  }
  finally {
    loading.value = false
  }
}

</script>


<style lang="less" scoped>
.update-time {
  font-weight: 400;
  font-size: 16px;
  color: #B3C0C8;
  line-height: 19px;
  text-align: center;
}
.login-btn{
  margin-top: 20px;
  margin-bottom: 24px;
}
</style>
